package com.hejia.alauda.service;

import com.hejia.alauda.entity.*;
import com.hejia.alauda.entity.example.DialogMessageExample;
import com.hejia.alauda.entity.example.MessageExample;
import com.hejia.alauda.entity.example.PushMessageExample;
import com.hejia.alauda.entity.example.SystemMessageExample;
import com.hejia.alauda.persistence.mybatis.DialogMessageMapper;
import com.hejia.alauda.persistence.mybatis.MessageMapper;
import com.hejia.alauda.persistence.mybatis.PushMessageMapper;
import com.hejia.alauda.persistence.mybatis.SystemMessageMapper;
import com.hejia.alauda.persistence.mybatis.UserMapper;
import com.hejia.alauda.utils.Pager;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 
 * 消息服务
 *
 *
 * Created by showone on 2014 下午4:30:06.
 *
 * @Copyright: 2014 www.hejiajinrong.com All rights reserved.
 */
@Service
public class MessageServiceImpl implements MessageService {

	@Resource
	private MessageMapper messageMapper;
	
	@Resource
	private SystemMessageMapper systemMapper;

	@Resource
	private UserMapper userMapper;

	@Resource
	private PushMessageMapper pushMessageMapper;
	
	@Resource
	private DialogMessageMapper dialogMessageMapper;

	/**
	 * 发送用户消息
	 * 
	 * @param receiverId
	 *            消息接收人ID
	 * @param title
	 *            消息标题
	 * @param content
	 *            消息内容
	 * @return
	 */
	public boolean sendMessage(Long receiverId, String title, String content,
			String url) {
		Message msg = new Message();
		User receiver = userMapper.selectByPrimaryKey(receiverId);
		if (receiver == null) {
			return false;
		}
		msg.setCreateDate(new Date());
		msg.setModifyDate(new Date());
		msg.setReceiver(receiver);
		msg.setTitle(title);
		msg.setContent(content);
		msg.setUrl(url);
		msg.setType(Message.MESSAGE_TYPE_USER);
		msg.setReadFlag(false);
		msg.setDeleteFlag(false);

		return messageMapper.insert(msg) > 0;
	}

	/**
	 * 设置消息已读
	 * 
	 * @param msgId
	 *            消息ID
	 * @return
	 */
	public boolean setMessageRead(Long userId, Long msgId) {
		Message msg = messageMapper.selectByPrimaryKey(msgId);
		if (msg == null) {
			return false;
		}
		if (msg.getReceiver().getId().longValue() != userId.longValue()) {
			return false;
		}
		msg.setReadFlag(true);
		return messageMapper.updateByPrimaryKey(msg) > 0;
	}

	public boolean deletemMessage(Long msgId) {
		Message msg = messageMapper.selectByPrimaryKey(msgId);
		if (msg == null) {
			return false;
		}
		msg.setDeleteFlag(true);
		return messageMapper.updateByPrimaryKey(msg) > 0;
	}

	/**
	 * 根据用户ID获取消息
	 * 
	 * @param userId
	 *            用户ID
	 * @param type
	 *            类型
	 * @return
	 */
	public Pager<Message> getMessageByUserId(Long userId, String type,
			Pager<Message> pager, Boolean readFlag) {

		// 插入系统消息
		insertSystemMessage(userId);
		
		MessageExample exp = new MessageExample();
		exp.appendCriterion("deleteFlag=", false);
		exp.appendCriterion("receiver_id=", userId);
		if (isNotBlank(type))
			exp.appendCriterion("type=", type);
		if (readFlag != null)
			exp.appendCriterion("readFlag=", readFlag.booleanValue());
		exp.setOrderByClause("createDate desc");

		pager.setTotalCount(messageMapper.countByExample(exp));
		if (pager.getPageCount() > 0) {
			pager.setList(messageMapper.selectByExample(exp, pager));
		}
		return pager;
	}

	/**
	 * 插入用户未获取的系统消息
	 * 
	 * @param userId
	 */
	private void insertSystemMessage(Long userId) {
		List<SystemMessage> list = systemMapper
				.getSystemMessageByReceiver(userId);

		for (int i = 0; i < list.size(); i++) {
			SystemMessage sm = list.get(i);
			Message msg = new Message();
			User receiver = new User();
			receiver.setId(userId);
			msg.setCreateDate(sm.getCreateDate());
			msg.setModifyDate(new Date());
			msg.setReceiver(receiver);
			msg.setMessage(sm);
			msg.setCategory(sm.getCategory());
			msg.setTitle(sm.getTitle());
			msg.setContent(sm.getContent());
			msg.setUrl(sm.getUrl());
			msg.setOpenAppPage(sm.getOpenAppPage());
			msg.setType(Message.MESSAGE_TYPE_SYSTEM);
			msg.setReadFlag(false);
			msg.setDeleteFlag(false);
			messageMapper.insert(msg);
		}
	}

	/**
	 * 发送系统消息
	 * 
	 * @param title
	 *            消息标题
	 * @param content
	 *            消息内容
	 * @param url
	 *            URL
	 * @return
	 */
	public boolean sendSystemMessage(String title, String content, String url,
			Date deadline) {
		SystemMessage msg = new SystemMessage();
		msg.setCreateDate(new Date());
		msg.setModifyDate(new Date());
		msg.setTitle(title);
		msg.setContent(content);
		msg.setUrl(url);
		if (deadline == null) {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH, 3);
			deadline = calendar.getTime();
		}
		msg.setDeadline(deadline);
		msg.setDeadFlag(false);
		msg.setPublishFlag(false);
		msg.setDeleteFlag(false);
		return systemMapper.insert(msg) > 0;
	}

	@Override
	public boolean publishSystemMessage(Long msgId) {
		SystemMessage msg = systemMapper.selectByPrimaryKey(msgId);
		if (msg == null) {
			return false;
		}
		msg.setPublishFlag(true);
		return systemMapper.updateByPrimaryKey(msg) > 0;
	}

	@Override
	public boolean setSystemMessageDead(Long msgId) {
		SystemMessage msg = systemMapper.selectByPrimaryKey(msgId);
		if (msg == null) {
			return false;
		}
		msg.setDeadFlag(true);
		return systemMapper.updateByPrimaryKey(msg) > 0;
	}

	@Override
	public void setSystemMessageDead() {
		systemMapper.setSystemMessageDead();
	}

	@Override
	public Pager<SystemMessage> findSystemMessage(SystemMessageExample exp,
			Pager<SystemMessage> pager) {
		if (pager == null) {
			pager = new Pager<SystemMessage>();
		}
		if (exp == null) {
			exp = new SystemMessageExample();
		}
		exp.appendCriterion("deleteFlag=", false);
		int count = systemMapper.countByExample(exp);
		pager.setTotalCount(count);
		if (count > 0) {
			List<SystemMessage> list = systemMapper.selectByExample(exp, pager);
			pager.setList(list);
		}

		return pager;
	}

	@Override
	public boolean deleteSystemMessage(Long msgId) {
		SystemMessage msg = systemMapper.selectByPrimaryKey(msgId);
		if (msg == null) {
			return false;
		}
		msg.setDeadFlag(true);
		msg.setDeleteFlag(true);
		return systemMapper.updateByPrimaryKey(msg) > 0;
	}

	@Override
	public SystemMessage getSystemMessage(Long msgId) {
		return systemMapper.selectByPrimaryKey(msgId);
	}

	@Override
	public boolean updateSystemMessage(SystemMessage msg) {
		msg.setModifyDate(new Date());
		return systemMapper.updateByPrimaryKey(msg) > 0;
	}

	@Override
	public Pager<Message> findMessage(MessageExample exp, Pager<Message> pager) {
		if (pager == null) {
			pager = new Pager<Message>();
		}
		if (exp == null) {
			exp = new MessageExample();
		}
		exp.appendCriterion("deleteFlag=", false);
		int count = messageMapper.countByExample(exp);
		pager.setTotalCount(count);
		if (count > 0) {
			List<Message> list = messageMapper.selectByExample(exp, pager);
			pager.setList(list);
		}

		return pager;
	}

	@Override
	public int havenew(Long userId) {
		insertSystemMessage(userId);

		MessageExample exp = new MessageExample();
		exp.appendCriterion("deleteFlag=", false);
		exp.appendCriterion("readFlag=", false);
		exp.appendCriterion("receiver_id=", userId);

		return messageMapper.countByExample(exp);
	}

	@Override
	public Message findMessageById(Long id) {
		return messageMapper.selectByPrimaryKey(id);
	}

	/**
	 * 传入"ios" 或者 "android" 查询对应系统的推送消息
	 *
	 * @param pager
	 *            分页
	 * @param models
	 *            系统机型
	 * @return 分页
	 */
	public Pager<PushMessage> listMessagesOfModels(Pager<PushMessage> pager,
			String models) {
		PushMessageExample example = new PushMessageExample();
		example.appendCriterion("models=", models);
		example.setOrderByClause("id desc");
		pager.setList(pushMessageMapper.selectByExample(example, pager));
		pager.setTotalCount(pushMessageMapper.countByExample(example));
		return pager;
	}

	/**
	 * 保存推送消息
	 *
	 * @param pushMessage
	 *            推送的消息
	 * @return 返回保存状态成功或者失败
	 */
	@Override
	public boolean savePushMessage(PushMessage pushMessage) {
		pushMessage.setModifyDate(new Date());
		return pushMessageMapper.insert(pushMessage) > 0;
	}

	/**
	 * 交易成功
	 *
	 * @param order
	 *            订单
	 */
	public void transactionSuccess(Order order) {
		Product product = order.getProduct();
		String content = "您已成功购买"
				+ product.getName().trim()
				+ "产品,金额"
				+ order.getAmount()
				+ "元,预期年化收益"
				+ (product.getInterestRate().doubleValue() + product
						.getBonusRate().doubleValue()) * 100 + "%,期限"
				+ product.getTerm() + "天,感谢您的支持。";

		sendMessage(order.getUser().getId(), "［交易成功］", content, null);
	}

	@Override
	public boolean sendAppMessage(User User, String category, String content,
			String url) {

		Message message = new Message();
		message.setCreateDate(new Date());
		message.setModifyDate(new Date());
		message.setReceiver(User);
		message.setTitle(category);
		message.setContent(content);
		message.setUrl(url);
		message.setType(Message.MESSAGE_TYPE_USER);
		message.setCategory(category);
		message.setReadFlag(false);
		message.setDeleteFlag(false);

		return messageMapper.insert(message) > 0;
	}

	@Override
	public boolean deletePersonMessage(Long msgId) {
		Message msg = messageMapper.selectByPrimaryKey(msgId);
		if (msg == null) {
			return false;
		}
		msg.setDeleteFlag(true);
		return messageMapper.updateByPrimaryKey(msg) > 0;
	}

	@Override
	public boolean sendAppMessage(User User, String category, String title, String content, String url, String openAppPage) {
		
		Message message = new Message();
		message.setCreateDate(new Date());
		message.setModifyDate(new Date());
		message.setReceiver(User);
		message.setCategory(category);
		message.setTitle(title);
		message.setContent(content);
		message.setUrl(url);
		message.setOpenAppPage(openAppPage);
		message.setType(Message.MESSAGE_TYPE_USER);
		message.setReadFlag(false);
		message.setDeleteFlag(false);

		return messageMapper.insert(message) > 0;
	}

	@Override
	public boolean sendSystemMessage(SystemMessage systemMessage) {
		
		SystemMessage message = new SystemMessage();
		message.setCreateDate(new Date());
		message.setModifyDate(new Date());
		message.setCategory(systemMessage.getCategory());
		message.setTitle(systemMessage.getTitle());
		message.setContent(systemMessage.getContent());
		message.setUrl(systemMessage.getUrl());
		message.setOpenAppPage(systemMessage.getOpenAppPage());
		if (systemMessage.getDeadline() == null) {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH, 3);
			systemMessage.setDeadline(calendar.getTime());
		}
		message.setDeadline(systemMessage.getDeadline());
		message.setDeadFlag(false);
		message.setPublishFlag(false);
		message.setDeleteFlag(false);
		
		return systemMapper.insert(message) > 0;
	}
	
	@Override
	public DialogMessage findDialogMessage(User user){
		
		if(user == null){
			//营销也可
			return null;
		}else{
			DialogMessageExample example = new DialogMessageExample();
			example.appendCriterion("user_id=", user.getId());
			example.appendCriterion("readTime is null");
			DialogMessage dm = dialogMessageMapper.selectOneByExample(example);
			if (dm!=null){
				dm.setReadTime(new Date());
				dialogMessageMapper.updateByPrimaryKey(dm);
			}
			return dm;
		}
		
	}

}
